<template>
  <div class="table-body-container layout-padding">
		<el-card shadow="hover" class="layout-padding-auto">
			<div class="system-user-search mb15">
        <el-input
          v-model="state.tableData.param.nodeName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter="handleQuery"
          class="search-input"
        />
        <el-select v-model="state.tableData.param.flowStatus" placeholder="请选择流程状态" clearable class="ml10 search-input">
          <el-option
            v-for="dict in flow_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
        <el-date-picker
          clearable
          v-model="state.tableData.param.createDate"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          class="ml10 search-input"
          placeholder="选择创建时间">
        </el-date-picker>
        <el-button type="primary" @click="handleQuery" class="ml10"><el-icon>
						<ele-Search />
					</el-icon>搜索</el-button>
        <el-button @click="resetQuery"><el-icon>
						<ele-Refresh />
					</el-icon>重置</el-button>
    </div>
 
    <el-table :data="state.tableData.data" v-loading="state.tableData.loading" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed />
      <el-table-column label="序号" width="55" align="center">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="流程实例id" align="center" prop="instanceId" :show-overflow-tooltip="true"/>
      <el-table-column label="流程名称" align="center" prop="flowName" :show-overflow-tooltip="true"/>
      <el-table-column label="任务名称" align="center" prop="targetNodeName" :show-overflow-tooltip="true"/>
      <el-table-column label="审批人" align="center" prop="approver" :show-overflow-tooltip="true"/>
      <el-table-column label="协作类型" align="center" prop="cooperateType" :show-overflow-tooltip="true">
        <template #default="scope">
          <dict-tag :options="cooperate_type" :value="scope.row.cooperateType"/>
        </template>
      </el-table-column>
      <el-table-column label="协作人" align="center" prop="collaborator" :show-overflow-tooltip="true"/>
      <el-table-column label="流程状态" align="center" prop="flowStatus" :show-overflow-tooltip="true">
        <template #default="scope">
          <dict-tag :options="flow_status" :value="scope.row.flowStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="审批时间" align="center" prop="createTime" width="160" :show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="110" fixed="right" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="small"
            type="text"
            @click="showDoneList(scope.row.instanceId, scope.row.formPath, scope.row.testLeaveVo)"
            v-auth="'flow:execute:doneList'"
          >审批记录</el-button>
          <el-button
            size="small"
            type="text"
            @click="toFlowImage(scope.row.instanceId)"
          >流程图</el-button>
          <el-button
            size="small"
            type="text"
            v-if="scope.row.ext"
            @click="handle(scope.row)"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
                v-show="state.tableData.total>0"
                :total="state.tableData.total"
                v-model:page="state.tableData.param.current"
                v-model:limit="state.tableData.param.size"
                @pagination="getList"
            />
    </el-card>

    <el-dialog title="流程图" width="70%" v-model="state.flowChart" append-to-body>
        <WarmChart :insId="state.insId"></WarmChart>
    </el-dialog>
    <component ref="componentRef" v-if="approve" :is="approve" :businessId="businessId" :taskId="taskId" :testLeaveVo="testLeaveVo" @refresh="getList"></component>
    <!-- 动态加载的组件 -->
    <el-dialog title="审批详情" :visible.sync="approveDialogVisible" width="80%">
      <component :is="dynamicComponent" v-if="dynamicComponent" :testLeaveVo="testLeaveVo" :taskId="taskId" :disabled="false"/>
    </el-dialog>
    <ApproveTableDialog ref="approveTableDialogRef" />
  </div>
</template>

<script setup lang="ts" name="Done">
import { donePage } from "/@/api/flow/execute";
import router from "/@/router";
import constConfig from '/@/utils/constConfig';

const WarmChart = defineAsyncComponent(() => import('/@/views/flow/definition/warm_chart.vue'));
const ApproveTableDialog = defineAsyncComponent(() => import('/@/views/flow/task/done/doneList.vue'));
const { proxy } = <any>getCurrentInstance();
const { flow_status, cooperate_type } = proxy.useDict('flow_status', 'cooperate_type');
const ids = ref([]);
const componentRef = ref();
const approveTableDialogRef = ref();

const state = reactive({
	tableData: {
		data: [],
		total: 0,
		loading: false,
		param: {
			nodeName: null,
      flowStatus: null,
      createBy: null,
      createDate: null,
			...constConfig.pageModel,
		},
	},
	formData: {
		username: '', // 账户名称
		nickName: '', // 用户昵称
		deptId: '', // 部门
		phone: '', // 手机号
		email: '', // 邮箱
		sex: '', // 性别
		status: '0', // 用户状态
		postIds: [],
        roleIds: []
	},
  insId: '',
  flowChart: false,
	...constConfig.dialogType
});
// 动态加载的组件相关
const approve = ref(null);
const dynamicComponent = ref(null);
const approveDialogVisible = ref(false);
const testLeaveVo = ref(null);
const taskId = ref(null);
const businessId = ref(null);
const single = ref(true);
const multiple = ref(true);


/** 查询流程实例列表 */
function getList() {
  state.tableData.loading = true;
  donePage(state.tableData.param).then(res => {
    state.tableData.data = res.data.records??[];
		state.tableData.total = res.data.total;
		state.tableData.loading = false;
  });
}
/** 搜索按钮操作 */
function handleQuery() {
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryForm");
  handleQuery();
}
// 多选框选中数据
function handleSelectionChange(selection:any) {
  ids.value = selection.map((item:any) => item.id)
  single.value = selection.length!==1
  multiple.value = !selection.length
}
/** 审批记录按钮操作 */
function showDoneList(instanceId:string, formPath:string, testLeaveVo:string) {
  approveTableDialogRef.value.openDialog(instanceId, formPath, testLeaveVo);

  // const params:any = { disabled: false, pageNum: state.tableData.param.current, formPath, testLeaveVo };
  // router.push({ path: `/done/done-list/index/${instanceId}`, query: params });
}
function toFlowImage(instanceId:string) {
  state.insId = instanceId;
  state.flowChart = true
}
function handle(row:any) {
  // 设置任务ID和业务ID
  taskId.value = row.id;
  businessId.value = row.businessId;

  // 解析ext字段的JSON数据
  // if (row.ext) {
  //   try {
  //     const parsedExt = JSON.parse(row.ext);
  //     testLeaveVo.value = { ...parsedExt };
  //   } catch (e) {
  //     console.error('Invalid ext JSON format:', row.ext);
  //   }
  // }

  // 获取或设置formPath路径
  const formPath = row.formPath;

  // 如果存在formPath，则动态加载组件
  if (formPath) {
    // 实际情况是，不同条件对应不同的页面，所以用动态导入组件
    import(/* @vite-ignore */`/@/views/${formPath}`).then((module) => {
      approve.value = module.default;
      nextTick(() => {
        componentRef.value.openDialog('50', businessId.value)
      })
    });
  } else {
    approve.value = null;
  }
}

// 页面加载时
onMounted(() => {
	getList();
});
</script>
<style scoped lang="scss">
.table-body-container {
	:deep(.el-card__body) {
		display: flex;
		flex-direction: column;
		flex: 1;
		overflow: auto;
		.el-table {
			flex: 1;
		}
	}
}
</style>